// ==UserScript==
// @name          NaNoWriMo Tools for Google Documents
// @namespace     tag:georgefox.edu,2005:pvandebr
// @description   A script to help automate the NaNoWriMo writing process by automatically posting word counts back to the NaNoWriMo servers when you save your document.
// @include       http://docs.google.com/Doc*
// @include       http://docs.google.com/Edit*
// @author        Pieter Vande Bruggen
// ==/UserScript==

var logged_in = false;
var nanowrimo_status = "";

// First we need to force a check for the document we're intending to update
// stats about.  Ideally this would be accomplished through tags, but for
// some reason, Google seems to have omitted the display and editing of 
// tags from inside the document editing interface itself.  While this is
// probably not a bad move, it's a little awkward.
if (document.getElementById('txtTitle').innerHTML.match(/\[nanowrimo\]/i))
{
	

	var doc_settings = document.evaluate('/HTML[1]/BODY[1]/FORM[1]/DIV[4]/TABLE[1]/TBODY[1]/TR[1]/TD[1]/TABLE[1]/TBODY[1]/TR[1]/TD[2]/TABLE[1]/TBODY[1]/TR[1]/TD[1]/A[1]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
	var nanowrimo_status = document.createElement("span");
	nanowrimo_status.innerHTML = '<span id="nanowrimo-status" style="color:#777; font-size: 0.8em">Verifying NaNoWriMo Status...</span>  | ';
	doc_settings.parentNode.insertBefore(nanowrimo_status, doc_settings);
	nanowrimo_status = nanowrimo_status.childNodes[0];
	
	GM_xmlhttpRequest({
	    method: 'GET',
	    url: 'http://www.nanowrimo.org/user.php',
	    headers: {
		'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
		'Accept': 'application/atom+xml,application/xml,text/xml'
	    },
	    onreadystatechange: function(x) { if (x.readyState == 4) check_logged_in(x); }
	});
	
	var save_button = document.getElementById('SaveButtonOn');
	save_button.addEventListener('click', update_word_count, true);
}

function update_word_count(e)
{
	var novel = document.getElementById('wys_frame').contentDocument.body.innerHTML;
	var wc = Math.ceil(novel.split(/\s+/).length * 0.98);
	
	if (logged_in) 
	{
		nanowrimo_status.innerHTML = "Updating word count...";
		
		GM_xmlhttpRequest({
		    method: 'POST',
		    url: 'http://www.nanowrimo.org/modules/wordcount/index.php',
		    headers: {
			'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
			'Accept': '',
			'Content-type':  'application/x-www-form-urlencoded'
		    },
		    data: "wordcount="+wc+"&op=update",
		    onload: function(x) { nanowrimo_status.innerHTML = "Word count updated: "+wc +" words"; }
		});
	}
}

function check_logged_in(x)
{
	logged_in = x.responseHeaders.match(/PHPSESSID/);
	nanowrimo_status.innerHTML = x.responseHeaders.match(/PHPSESSID/) ? 
		"Logged in to NaNoWriMo" : 
		"Please log in to NaNoWriMo";
}